package com.campus.help.controller;

import com.campus.help.entity.User;
import com.campus.help.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> req, HttpSession session) {
        String studentId = req.get("studentId");
        String password = req.get("password");
        Optional<User> userOpt = userService.findByStudentId(studentId);
        Map<String, Object> resp = new HashMap<>();
        if (userOpt.isPresent() && userOpt.get().getPassword().equals(password)) {
            session.setAttribute("user", userOpt.get());
            resp.put("success", true);
            resp.put("user", userOpt.get());
        } else {
            resp.put("success", false);
            resp.put("message", "学号或密码错误");
        }
        return resp;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> resp = new HashMap<>();
        if (userService.existsByStudentId(user.getStudentId())) {
            resp.put("success", false);
            resp.put("message", "学号已存在");
        } else {
            userService.save(user);
            resp.put("success", true);
        }
        return resp;
    }

    @PostMapping("/logout")
    public Map<String, Object> logout(HttpSession session) {
        session.invalidate();
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", true);
        return resp;
    }

    @GetMapping("/me")
    public Map<String, Object> me(HttpSession session) {
        Map<String, Object> resp = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            resp.put("success", true);
            resp.put("user", user);
        } else {
            resp.put("success", false);
        }
        return resp;
    }
} 